package com.loyal.mwm.ui

import android.content.Intent
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.View
import com.base.kit.TimeUtil
import com.loyal.mwm.R
import com.loyal.mwm.adapter.WeatherAdapter
import com.loyal.mwm.base.BaseSwipeActivity
import com.loyal.mwm.beans.WeatherBean
import com.loyal.mwm.databinding.ActivityWeatherBinding
import com.loyal.mwm.impl.IContactImpl
import com.loyal.mwm.util.ImageUtil
import com.loyal.mwm.util.PreferUtil
import com.loyal.mwm.util.WeatherUtil
import java.lang.ref.WeakReference

class WeatherActivity : BaseSwipeActivity<ActivityWeatherBinding>(), View.OnClickListener {
    private var mHandler: HandlerClass? = null
    private val beanList: List<WeatherBean.DataBean.ForecastBean> = ArrayList()
    private var weatherAdapter: WeatherAdapter? = null

    override fun actLayoutRes(): Int {
        return R.layout.activity_weather
    }

    override fun afterOnCreate() {
        val toolbar = binding.toolbar.root
        toolbar.title = getString(R.string.MwMWeather)
        setSupportActionBar(toolbar)
        binding.drawable = ImageUtil.getBackground(this)
        mHandler = HandlerClass(this)
        initViews()
    }

    private fun initViews() {
        var city = intent.getStringExtra("city")
        city = if (TextUtils.isEmpty(city)) "西安" else city
        binding.city = city
        binding.dateTime = TimeUtil.getDateTime(TimeUtil.TIME_WEEK)
        binding.gridWeather.adapter = WeatherAdapter(
            beanList
        ).also { weatherAdapter = it }
        if (city!!.endsWith("市")) city = city.substring(0, city.length - "市".length)
        WeatherUtil.getCityWeather(city, mHandler)
    }

    override fun setEdgePosition(): Int {
        return LEFT
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.text_change_city -> {
                val intent = Intent(this,  CityActivity::class.java)
                startActivityForResult(intent, IContactImpl.IntImpl.reqCodeCity)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) return
        when (requestCode) {
            IContactImpl.IntImpl.reqCodeCity -> {
                val cityName = data?.getStringExtra("cityName")
                if (TextUtils.isEmpty(cityName)) return
                binding.city = cityName
                PreferUtil.putString(applicationContext, IContactImpl.StrImpl.KEY_CITY, cityName)
                WeatherUtil.getCityWeather(cityName, mHandler)
            }
        }
    }

    override fun onBackPressed() {
        setResult(RESULT_OK, Intent())
        finish()
        super.onBackPressed()
    }

    private class HandlerClass(activity: WeatherActivity) : Handler() {
        private val weakReference: WeakReference<WeatherActivity>

        init {
            weakReference = WeakReference(activity)
        }

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val activity = weakReference.get()
            when (msg.what) {
                IContactImpl.IntImpl.rx2Weather -> {
                    val weatherBean = msg.obj as WeatherBean? ?: return
                    try {
                        val wendu = weatherBean.data.wendu
                        activity?.binding?.temperCurrent = "$wendu°"
                        val weather = weatherBean.data.forecast[0].type
                        val high = weatherBean.data.forecast[0].high
                        val low = weatherBean.data.forecast[0].low
                        activity?.binding?.weatherAndTemper = "$weather      " + low.replace(
                            "低温",
                            ""
                        ).trim() + "/" + high.replace("高温", "").trim()
                        activity?.binding?.weatherImg = ImageUtil.getBackground(
                            activity,
                            R.mipmap.ic_weather_cloudy,
                            false
                        )
                        activity?.binding?.ganmao = weatherBean.data.ganmao
                        activity?.weatherAdapter?.notifyList(
                            weatherBean.data.forecast
                        )
                    } catch (e: Exception) {
                        //OutUtil.println("Handler::$e")
                    }
                }
            }
        }
    }
}